<template>
  <div class="home-container page-container" ref="homeView">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><DataAnalysis/></el-icon>
                学习统计
              </span>
              <el-button
                  type="text"
                  @click="refreshData"
                  :icon="Refresh"
                  class="refresh-btn"
                  :loading="loading"
              >
                刷新
              </el-button>
            </div>
          </template>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">总笔记数</div>
              <div class="stat-value">{{ totalNotes }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已完成复习</div>
              <div class="stat-value">{{ completedReviews }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">待复习</div>
              <div class="stat-value">{{ pendingReviews }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">复习完成率</div>
              <div class="stat-value">{{ reviewCompletionRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="quick-actions-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Lightning/></el-icon>
                快捷操作
              </span>
            </div>
          </template>
          <div class="actions-content">
            <el-button
                type="primary"
                size="large"
                @click="goToNotes"
                :icon="Notebook"
                class="action-btn"
            >
              管理笔记
            </el-button>
            <el-button
                type="success"
                size="large"
                @click="addNoteDialogVisible = true"
                :icon="Plus"
                class="action-btn"
            >
              添加笔记
            </el-button>
            <el-button
                type="warning"
                size="large"
                @click="checkTodayReviews"
                :icon="Bell"
                class="action-btn"
                :loading="checkLoading"
            >
              检查复习
            </el-button>
          </div>
        </el-card>

        <el-card class="recent-notes-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Document/></el-icon>
                最近笔记
              </span>
              <el-button
                  type="text"
                  @click="goToNotes"
                  :icon="ArrowRight"
                  class="view-all-btn"
              >
                查看全部
              </el-button>
            </div>
          </template>
          <div class="recent-notes">
            <el-table
                :data="recentNotes"
                style="width: 100%"
                empty-text="暂无笔记"
                :show-header="false"
                v-loading="loading"
            >
              <el-table-column width="40">
                <template #default>
                  <el-icon>
                    <Document/>
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column prop="title" min-width="200">
                <template #default="{ row }">
                  <el-link
                      :href="row.yuqueUrl"
                      target="_blank"
                      type="primary"
                      class="note-title"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" width="100">
                <template #default="{ row }">
                  <span class="create-time">{{ formatDate(row.createdAt) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="folder" width="120">
                <template #default="{ row }">
                  <el-tag v-if="row.folder" size="small" class="folder-tag">
                    {{ row.folder }}
                  </el-tag>
                  <span v-else class="no-folder">未分类</span>
                </template>
              </el-table-column>
              <el-table-column width="80">
                <template #default="{ row }">
                  <el-progress
                      :percentage="calculateReviewProgress(row.reviewSchedules)"
                      :show-text="false"
                      class="progress-bar"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加笔记对话框 -->
    <add-note-dialog
        v-model="addNoteDialogVisible"
        @success="handleNoteAdded"
    />
  </div>
</template>

<script>
import { ref, onMounted, computed, inject, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import AddNoteDialog from '@/components/AddNoteDialog.vue'
import { getNotes, checkTodayReviews as checkReviewsAPI } from '@/api/notes'
import dayjs from 'dayjs'

export default {
  name: 'HomeView',
  components: {
    AddNoteDialog
  },
  setup() {
    const router = useRouter()

    // 注入全局刷新函数
    const refreshAllData = inject('refreshAllData')

    // 原有状态定义
    const totalNotes = ref(0)
    const completedReviews = ref(0)
    const pendingReviews = ref(0)
    const recentNotes = ref([])
    const addNoteDialogVisible = ref(false)
    const loading = ref(false)
    const checkLoading = ref(false)

    // 计算复习完成率
    const reviewCompletionRate = computed(() => {
      const total = completedReviews.value + pendingReviews.value
      return total > 0 ? Math.round((completedReviews.value / total) * 100) : 0
    })

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        console.log('开始加载首页数据...')
        const response = await getNotes()

        if (response.success) {
          const notes = response.data
          totalNotes.value = notes.length
          recentNotes.value = notes.slice(0, 5)

          // 计算复习统计
          let completed = 0
          let pending = 0
          notes.forEach(note => {
            if (note.reviewSchedules) {
              note.reviewSchedules.forEach(schedule => {
                if (schedule.completed) {
                  completed++
                } else {
                  pending++
                }
              })
            }
          })
          completedReviews.value = completed
          pendingReviews.value = pending

          console.log('首页数据加载完成', {
            totalNotes: totalNotes.value,
            completedReviews: completedReviews.value,
            pendingReviews: pendingReviews.value
          })
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    // 手动刷新数据
    const refreshData = async () => {
      await loadData()
      ElMessage.success('数据刷新成功')
    }

    // 监听全局刷新事件
    const handleGlobalRefresh = async () => {
      console.log('收到全局刷新请求，刷新首页数据...')
      await loadData()
    }

    // 前往笔记管理页面
    const goToNotes = () => {
      router.push('/notes')
    }

    const checkTodayReviews = async () => {
      if (checkLoading.value) return

      checkLoading.value = true
      try {
        const response = await checkReviewsAPI()
        if (response.success) {
          const count = response.data.count
          if (count > 0) {
            ElMessage.success(`今天有 ${count} 条笔记需要复习`)
          } else {
            ElMessage.success('今天没有需要复习的笔记')
          }
        }
      } catch (error) {
        ElMessage.error('检查复习任务失败')
      } finally {
        checkLoading.value = false
      }
    }

    const handleNoteAdded = () => {
      loadData()
      addNoteDialogVisible.value = false
    }

    const calculateReviewProgress = (schedules) => {
      if (!schedules || schedules.length === 0) return 0
      const completed = schedules.filter(s => s.completed).length
      return Math.round((completed / schedules.length) * 100)
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    onMounted(() => {
      loadData()

      // 如果存在全局刷新函数，设置监听
      if (refreshAllData) {
        // 创建一个包装函数来同时处理全局刷新和本地刷新
        const globalRefreshHandler = async () => {
          await handleGlobalRefresh()
        }

        // 存储原始函数以便清理
        window._homeRefreshHandler = globalRefreshHandler

        // 注意：这里我们不再重新赋值 refreshAllData，而是直接使用它
        console.log('首页已注册全局刷新监听')
      }
    })

    onUnmounted(() => {
      // 清理工作
      if (window._homeRefreshHandler) {
        delete window._homeRefreshHandler
      }
    })

    return {
      totalNotes,
      completedReviews,
      pendingReviews,
      reviewCompletionRate,
      recentNotes,
      addNoteDialogVisible,
      loading,
      checkLoading,
      goToNotes,
      checkTodayReviews,
      handleNoteAdded,
      calculateReviewProgress,
      formatDate,
      loadData,
      refreshData
    }
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;
}
.stats-card, .quick-actions-card, .recent-notes-card {
  min-height: 200px;
}
.stats-card {
  height: 100%;

  .stats-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 10px 0;
  }
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
}

.refresh-btn {
  color: #409eff;
}

.actions-content {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  padding: 10px 0;
}

.action-btn {
  min-width: 120px;
  font-weight: 500;
}

.recent-notes {
  min-height: 200px;
}

.note-title {
  font-weight: 500;
}

.create-time {
  color: #909399;
  font-size: 12px;
}

.folder-tag {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-folder {
  color: #c0c4cc;
  font-size: 12px;
}

.progress-bar {
  width: 60px;
}

.view-all-btn {
  color: #409eff;
  font-weight: 500;
}

// 响应式设计
@media (max-width: 768px) {
  .home-container {
    padding: 16px;
  }

  .stats-card {
    margin-bottom: 20px;
  }

  .actions-content {
    flex-direction: column;

    .action-btn {
      width: 100%;
    }
  }

  .recent-notes-card {
    .card-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
  }
}
</style>